/**
 * @Description: 邮箱动态设置
 * @author 殷佳乐
 * @date 2019/11/5 下午17:21
 */
import {
  Button,
  Form,
  Input,
  Select,
  Upload,
  message,
  Col,
  Row,
  AutoComplete,
  Radio,
  Checkbox,
  Divider,
  Card,
  notification,
} from 'antd';
import Modal from 'drag-modal';
// eslint-disable-next-line import/no-extraneous-dependencies
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { rulesReg } from '../../../utils/uiUtils';
import { getWebPath } from '../../../utils/request';
import { requestLists, requestPromise } from '@/utils/request';

const FormItem = Form.Item;
const { Option } = Select; // 头像组件 方便以后独立，增加裁剪之类的功能

@connect(({ accountAndsettings }) => ({
  // currentUser: accountAndsettings.currentUser,
  currentUser: '',
}))
class MailSetting extends Component {
  mailSuffix = ['163.com', '126.com', 'gmail.com', 'qq.com', 'hotmail.com', 'sohu.com', 'sina.com'];

  view = undefined;

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      mailInfo: [],
      checked: false,
      loading: false,
    };
  }

  componentDidMount() {
    this.getMailInfo();
  }

  getMailInfo = () => {
    requestPromise(`${getWebPath('sys/config/email/getMailInfo')}`, {
      method: 'GET',
    }).then(res => {
      if (res.code === 0) {
        this.setState({
          mailInfo: res.mailInfo,
          checked: res.mailInfo.ssl,
        });
      }
    });
  };

  getAvatarURL() {
    const { currentUser } = this.props;

    if (currentUser) {
      if (currentUser.avatar) {
        return currentUser.avatar;
      }

      const url = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      return url;
    }

    return '';
  }

  getViewDom = ref => {
    this.view = ref;
  };

  handlerSubmit = event => {};

  showModal = () => {
    this.setState({
      visible: true,
      successMsg: 'none',
    });
  };

  handleOk = e => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const info = this.props.form.getFieldsValue();
        requestPromise(`${getWebPath('sys/config/email/setMailInfo')}`, {
          method: 'POST',
          body: info,
        }).then(res => {
          if (res.code === 0) {
            this.setState({
              visible: false,
              mailInfo: res.mailInfo,
            });
          }
        });
      }
    });
  };

  handleCancel = e => {
    this.setState({
      visible: false,
    });
  };

  onChange = e => {
    this.setState({
      checked: e.target.checked,
    });
  };

  testEmail = () => {
    const info = this.props.form.getFieldsValue();
    this.setState({
      successMsg: 'none',
      loading: true,
    });
    requestPromise(`${getWebPath('sys/config/email/SendTestEmail')}`, {
      method: 'POST',
      body: info,
    }).then(res => {
      if (res.code === 0) {
        this.setState({
          successMsg: 'block',
        });
      }
      this.setState({
        loading: false,
      });
    });
  };

  autoCompleteHandleSearch = value => {
    this.setState({
      mailDataSource:
        !value || value.indexOf('@') === -1
          ? []
          : this.mailSuffix
              .map(en => `${value.split('@', 2)[0]}@${en}`)
              .filter(en => en.indexOf(value.split('@', 2)[1]) !== -1),
    });
  };

  render() {
    const ItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 }, //5+19=24,少一个栅格
    };
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 17 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 24, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    const {
      form: { getFieldDecorator },
    } = this.props;
    const model = this.state.mailInfo;
    console.log(model);

    return (
      <div>
        <Modal
          title="设置发件服务器"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={600}
          okText="保存并应用"
          cancelText="取消"
        >
          <Form layout="horizontal">
            <Row gutter={{ ...rowGutterPxLayout }}>
              <Col {...colSpanLayout}>
                <FormItem label="服务器地址：" {...formItemLayout}>
                  {getFieldDecorator('host', {
                    initialValue: model.host,
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                    ],
                  })(<Input type="text" maxLength={50} placeholder="服务器地址" />)}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem label="SMTP端口号：" {...formItemLayout}>
                  {getFieldDecorator('port', {
                    initialValue: model.port,
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                      rulesReg('digits'),
                    ],
                  })(
                    <Input
                      type="text"
                      maxLength={10}
                      style={{ width: 100 }}
                      autocomplete="off"
                      placeholder="SMTP端口号"
                    />
                  )}
                  {getFieldDecorator('ssl', {
                    initialValue: true,
                  })(
                    <Checkbox
                      checked={this.state.checked}
                      style={{ float: 'right' }}
                      onChange={this.onChange}
                    >
                      使用SSL
                    </Checkbox>
                  )}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem label="发件人邮箱：" {...formItemLayout}>
                  {getFieldDecorator('username', {
                    initialValue: model.username,
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                      rulesReg('email'),
                    ],
                  })(
                    <AutoComplete
                      type="text"
                      maxLength={200}
                      autocomplete="off"
                      placeholder="发件人邮箱"
                      dataSource={this.state.mailDataSource}
                      onSearch={this.autoCompleteHandleSearch}
                    />
                  )}
                </FormItem>
              </Col>
              <Col {...colSpanLayout}>
                <FormItem label="发件人邮箱密码：" {...formItemLayout}>
                  {getFieldDecorator('password', {
                    initialValue: model.password,
                    rules: [
                      {
                        required: true,
                        message: '必填',
                      },
                    ],
                  })(
                    <Input.Password
                      type="text"
                      maxLength={200}
                      autocomplete="off"
                      placeholder="密码/授权码"
                    />
                  )}
                </FormItem>
              </Col>
              <Divider />
              <Col {...colSpanLayout}>
                <FormItem label="测试收件人邮箱：" {...formItemLayout}>
                  {getFieldDecorator('testMail', {
                    rules: [rulesReg('email')],
                  })(<Input type="text" autocomplete="off" placeholder="收件人邮箱" />)}
                  <Button
                    type="primary"
                    style={{ float: 'right' }}
                    onClick={this.testEmail}
                    loading={this.state.loading}
                  >
                    发送测试邮件
                  </Button>
                </FormItem>
              </Col>
              <Col
                {...colSpanLayout}
                style={{ display: this.state.successMsg, backgroundColor: '#b6f8b6' }}
              >
                <p>邮件发送成功！</p>
                <p>
                  请到您的邮箱中检查测试邮件是否收到，如未收到，请注意检查测试邮件是否被归为垃圾邮件。
                </p>
              </Col>
            </Row>
          </Form>
        </Modal>

        <div layout="vertical" hideRequiredMark>
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="SMTP服务器:" {...ItemLayout}>
                {model.host}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="SMTP端口:" {...ItemLayout}>
                {model.port}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="SSL模式:" {...ItemLayout}>
                {model.ssl ? '是' : '否'}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="发件人邮箱:" {...ItemLayout}>
                {model.username}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <Button type="primary" onClick={this.showModal}>
                <FormattedMessage
                  id="accountandsettings.basic.update"
                  defaultMessage="设置发件服务器"
                />
              </Button>
            </Col>
          </Row>
        </div>
      </div>
    );
  }
}

export default Form.create()(MailSetting);
